package api

import (
	"common/config"
	"common/utils"
	"encoding/json"
	"errors"
	"fmt"
	uuid "github.com/satori/go.uuid"
	"github.com/wangluozhe/requests"
	"github.com/wangluozhe/requests/url"
	"io"
	"os"
	"path/filepath"
	"strings"
)

type ObsRes struct {
	Code    int64  `json:"code"`
	Data    any    `json:"data"`
	Message string `json:"msg"`
	Success bool   `json:"success"`
}

func ObsUpload(filePath string) (string, error) {
	conf, _ := config.LoadObsConfig()
	uri := fmt.Sprintf("%v%v", conf.Host, "/api/upload")
	headers := url.NewHeaders()
	req := url.NewRequest()
	files := url.NewFiles()
	sm4 := utils.GetSM4EncryptInstance(conf.SM4Key, conf.SM4Iv)
	fname := filepath.Base(filePath)
	files.SetFile("file", fname, filePath, "")
	Authorization, _ := sm4.Encrypt(uuid.NewV4().String())
	headers.Set("Authorization", Authorization)
	req.Files = files
	req.Headers = headers
	r, err := requests.Post(uri, req)
	if err != nil {
		panic(err.Error())
	}
	var response ObsRes

	err1 := json.Unmarshal([]byte(r.Text), &response)
	if err1 != nil {
		panic(err.Error())
	}
	if response.Success != true {
		panic(fmt.Sprintf("%v", response.Data))
	}

	return response.Data.(map[string]interface{})["fileId"].(string), nil

}

func ObsDownload(fileId string, filePath string) error {
	conf, _ := config.LoadObsConfig()
	uri := fmt.Sprintf("%v%v", conf.Host, "/api/download")
	sm4 := utils.GetSM4EncryptInstance(conf.SM4Key, conf.SM4Iv)
	headers := url.NewHeaders()
	params := url.NewParams()
	params.Set("fileId", fileId)
	Authorization, _ := sm4.Encrypt(uuid.NewV4().String())
	headers.Set("Authorization", Authorization)
	req := url.NewRequest()
	req.Headers = headers
	req.Params = params
	r, err := requests.Get(uri, req)
	if err != nil {
		return err
	}
	ContentType := r.Headers.Get("Content-Type")
	if strings.Contains(ContentType, "json") {
		return errors.New("obs文件下载失败")
	}
	fileByte, _ := io.ReadAll(r.Body)
	os.WriteFile(filePath, fileByte, 0666)
	return nil
}

func ObsUrl(fileId string) string {
	conf, _ := config.LoadObsConfig()
	uri := fmt.Sprintf("%v%v", conf.Host, "/api/getUrl")
	sm4 := utils.GetSM4EncryptInstance(conf.SM4Key, conf.SM4Iv)
	headers := url.NewHeaders()
	params := url.NewParams()
	params.Set("fileId", fileId)
	Authorization, _ := sm4.Encrypt(uuid.NewV4().String())
	headers.Set("Authorization", Authorization)
	req := url.NewRequest()
	req.Headers = headers
	req.Params = params
	r, err := requests.Get(uri, req)
	if err != nil {
		panic(err.Error())
	}
	var response ObsRes

	err1 := json.Unmarshal([]byte(r.Text), &response)
	if err1 != nil {
		panic(err.Error())
	}

	if response.Success != true {
		panic(fmt.Sprintf("%v", response.Data))
	}
	return response.Data.(map[string]interface{})["fileUrl"].(string)

}
